package com.example.zg.learn;

import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.zg.learn.enties.Author;
import com.example.zg.learn.enties.Book;
import com.example.zg.learn.enties.Reader;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * Parcelable 序列化接口
 * 切换横竖屏 数据用保存的初始化
 */
public class ParcelableActivity extends AppCompatActivity {
    private Book book;
    private TextView[] texts;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();

        if(savedInstanceState!=null){
            book=savedInstanceState.getParcelable("book");
        }
        if(book==null){
            initData();
        }
        BindData();

    }

    private void initView(){
        LinearLayout ll=findViewById(R.id.textGroup);
        texts=new TextView[ll.getChildCount()];
        for(int i=0;i<ll.getChildCount();i++){
            texts[i]= (TextView) ll.getChildAt(i);
        }
    }

    private void initData(){
        book=new Book("大话西游",30.25,new Author("周星星"),false);
        book.setTags(new String[]{"搞笑","动作","神话"});
        book.setReaders(Arrays.asList(new Reader("张珊"),new Reader("李四"),new Reader("王五")));

    }

    private void BindData(){
        if(book!=null){
            texts[0].setText(book.getName());
            texts[1].setText(book.getPrice() + "");
            if (book.getAuthor() != null) {
                texts[2].setText(book.getAuthor().getName());
            }
            texts[3].setText(book.isFinish() ? "完本" : "正在更新");

            if (book.getTags() != null) {
                String s = "";
                for (String tag : book.getTags()) {
                    s += tag + "_";
                }
                s = s.substring(0, s.length()-1);
                texts[4].setText(s);
            }
            if (book.getReaders() != null) {
                String s = "";
                for (Reader reader : book.getReaders()) {
                    s += reader.getName() + "_";
                }
                s = s.substring(0, s.length()-1);
                texts[5].setText(s);
            }

        }

    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putParcelable("book",book);
    }

    public void changeBook(View view) {
        book=new Book("大话西游222222",301.25,new Author("周星星222"),true);
        book.setTags(new String[]{"搞笑222","动作22","神话22"});
        book.setReaders(Arrays.asList(new Reader("张珊222"),new Reader("李四222"),new Reader("王五22")));
        BindData();
    }
}
